package middle;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Solution_179 {

    public String largestNumber(int[] nums) {
        boolean zero = true;
        List<Integer> list = new ArrayList<>();
        for (int num : nums) {
            list.add(num);
            if (zero && num != 0) {
                zero = false;
            }
        }
        if (zero) {
            return "0";
        }
        List<Integer> collect = list.stream().sorted((e1, e2) -> dps(String.valueOf(e1), String.valueOf(e2))).collect(Collectors.toList());
        StringBuilder builder = new StringBuilder();
        for (Integer num : collect) {
            builder.append(num);
        }
        return builder.toString();
    }

    private int dps(String a, String b) {
        for (int i = 0; i < a.length() || i < b.length(); i++) {
            if (i < a.length() && i < b.length()) {
                char aa = a.charAt(i), bb = b.charAt(i);
                if (aa > bb) {
                    return -1;
                } else if (aa < bb) {
                    return 1;
                }
            } else {
                String m = a.substring(0, i);
                if (a.length() > b.length()) {
                    String n = a.substring(i);
                    return dps(n, m);
                } else {
                    String n = b.substring(i);
                    return dps(m, n);
                }
            }
        }
        return 0;
    }

    public static void main(String[] args) {
        Solution_179 model = new Solution_179();
//        List<String> list = new ArrayList<>();
//        list.add("432");
//        list.add("43243");
//        list.sort(model::dps);
//        System.out.println(list);
//        System.out.println(model.largestNumber(new int[]{0, 0}));
//        System.out.println(model.largestNumber(new int[]{0, 1}));
//        System.out.println(model.largestNumber(new int[]{10, 2}));
        System.out.println(model.largestNumber(new int[]{3, 30, 34, 5, 9}));

//        System.out.println(model.largestNumber(new int[]{432, 43243}));
        // 432 43 432
        // 432 43 243
    }
}
